package cqrtplm.service.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.basic.dto.TyplmCommonQueryDTO;
import com.hustcad.plm.pdm.flowbusiness.service.TyplmPBOProcessHistoryQueryService;
import com.hustcad.plm.pdm.workflow.model.vo.FlowObjectDetailInfoVO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.ArgumentUtils;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.DspfDemandDevpDTO;
import cqrtplm.dto.RtCfgDemandOrdersDTO;
import cqrtplm.dto.query.DspfDemandDevplanQueryDTO;
import cqrtplm.entity.DspfDemandDevplanDO;
import cqrtplm.entity.DspfDemandDevplanEditLogDO;
import cqrtplm.entity.RtTestRequirementsDO;
import cqrtplm.mapper.DspfDemandDevplanMapper;
import cqrtplm.mapper.RtCfgDemandOrdersMapper;
import cqrtplm.mapper.RtCfgStatusInfoMapper;
import cqrtplm.service.FlowControlService;
import cqrtplm.service.IDspfDemandDevplanService;
import cqrtplm.util.WorkingDayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 需求排程Service业务层处理
 *
 * @author 江小雄
 * @date 2025-06-23
 */
@Service
public class DspfDemandDevplanServiceImpl implements IDspfDemandDevplanService
{
    @Autowired
    private DspfDemandDevplanMapper dspfDemandDevplanMapper;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private RtCfgDemandOrdersMapper rtCfgDemandOrdersMapper;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Resource
    private WorkingDayUtil workingDayUtil;
    @Resource
    private TyplmPBOProcessHistoryQueryService typlmProcessQueryService;
    @Resource
    private FlowControlService flowControlService;

    /**
     * 查询需求排程
     *
     * @param DevPlanID 需求排程主键
     * @return 需求排程
     */
    @Override
    public DspfDemandDevplanDO selectDspfDemandDevplanByDevPlanID(String DevPlanID)
    {
        return dspfDemandDevplanMapper.selectDspfDemandDevplanByDevPlanID(DevPlanID);
    }




    /**
     * 新增需求排程
     *
     * @param
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insertDspfDemandDevplan(DspfDemandDevpDTO dto)
    {
        List<RtCfgDemandOrdersDTO> list = dto.getList();
        //根据无需处理的节点id进行流程设置，且要自动处理状态室分配节点
        List<String> flownodeauth = dto.getFlownodeauth();
//        if(IterUtil.isNotEmpty(flownodeauth)) {
//            //获取当前处理流程节点对象信息
//            String oid = rtCfgStatusInfoMapper.selectOidByStatausId(list.get(0).getStatusid());
//            TyplmCommonQueryDTO queryDTO = new TyplmCommonQueryDTO();
//            queryDTO.setOid(new BigInteger(oid));
//            queryDTO.setQueryType("currentVersion");
//            queryDTO.setOtype("ty.inteplm.part.CTyPart");
//            ArgumentUtils.checkArgumentNull(queryDTO, "queryDTO");
//            List<FlowObjectDetailInfoVO> flowObjectDetailInfoList = this.typlmProcessQueryService.queryProcessListByObject(queryDTO);
//            flowObjectDetailInfoList.stream().filter(flowObjectDetailInfoVO -> "流程中".equals(flowObjectDetailInfoVO.getStatusName()));
//            // 根据流程容器id查询当前节点信息
//            if (flowObjectDetailInfoList.size() == 1) {
//                String workFlowContainerId = flowObjectDetailInfoList.get(0).getWorkFlowContainerOid().toString();
//                com.alibaba.fastjson.JSONObject param = new com.alibaba.fastjson.JSONObject();
//                param.put("workFlowContainerId", workFlowContainerId);
//                param.put("route", "通过");
//                try {
//                    flowControlService.completedPlanChangWorkFlow(param);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        if(IterUtil.isNotEmpty(list)){
            list.stream().forEach(i->{
                DspfDemandDevplanDO dspfDemandDevplanDO = new DspfDemandDevplanDO(i,dto);
                dspfDemandDevplanDO.setDevPlanID(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
                dspfDemandDevplanDO.setCreateUser(TyAccountContext.getUser().getName());
                dspfDemandDevplanDO.setCreateDate(new Date());
                if(IterUtil.isNotEmpty(flownodeauth)){
                    dspfDemandDevplanDO.setFlownodeauthstr(String.join(",", flownodeauth));
                }
                dspfDemandDevplanMapper.insertDspfDemandDevplan(dspfDemandDevplanDO);
                //将动力负责人，机组负责人反写到需求状态表上 todo 取消此逻辑
//                rtCfgStatusInfoMapper.updateManagerByXqCode(dto);

                //创建在途数据之后删掉待排程数据
                rtCfgDemandOrdersMapper.updateIsDeleteByOrdersId(i.getId());
            });
        }
        return ResponseResult.success("操作成功");
    }

    /**
     * 修改需求排程
     *
     * @param
     * @return 结果
     */
    @Override
    public ResponseResult updateDspfDemandDevplan(DspfDemandDevpDTO dto)
    {
        /*
        *  排程调整业务逻辑
        *   1.将调整的变更延期原因追加到之前的原因里面
        *   2.更改预估完成时间
        *   3.将更改的这条数据添加到排程调整历史表
        * */

        DspfDemandDevplanDO dspfDemandDevplanDO = dspfDemandDevplanMapper.selectDspfDemandDevplanByDevPlanID(
                dto.getDevPlanID());
        //顺延逻辑
        Integer extensionDay = dto.getExtensionDay();
        Date estimatedCompletionTime = dto.getEstimatedCompletionTime();
        JSONObject jsonObject = workingDayUtil.getCalendarExceptionAndWeekDayByProjectOid();
        if(extensionDay!=null){
            /*
            * 顺延需要跳过工作日
            *   1.判断是否不在工作周内
            *   2.判断是否在不在例外工作日期之间
            * */
            Date date = new Date();
            if(!jsonObject.isEmpty()){
                List<Integer> weekDays = workingDayUtil.getWeekDays(jsonObject);
                for (int i = 1; i <= extensionDay; i++) {
                    DateTime dateTime = DateUtil.offsetDay(date, i);
                    int value = dateTime.dayOfWeekEnum().getValue();
                    if(weekDays.contains(value)){
                        extensionDay = extensionDay + 1;
                    }
                }
            }

            dspfDemandDevplanDO.setEstimatedCompletionTime(DateUtil.offsetDay(date, extensionDay));

        }else {
            if(!jsonObject.isEmpty()){
                List<JSONObject> exceptions = workingDayUtil.getExceptions(jsonObject);
                if(IterUtil.isNotEmpty(exceptions)){
                    for (JSONObject json:exceptions){
                        //非工作日开始时间
                        DateTime fromDate = DateUtil.parse(json.get("FromDate").toString());
                        //非工作日结束时间
                        DateTime toDate = DateUtil.parse(json.get("ToDate").toString());
                        boolean isInRange = DateUtil.isIn(estimatedCompletionTime, fromDate, toDate);
                        if(isInRange){
                            throw  RTErrorCodeEnum.STATUS_INFO_CONTENT_IS_NULL.getException("当前顺延时间"+DateUtil.formatDate(estimatedCompletionTime)+"在项目管理中设置的是非工作日请重新选择！");
                        }
                    }
                }
            }

            dspfDemandDevplanDO.setEstimatedCompletionTime(estimatedCompletionTime);
        }
        dspfDemandDevplanDO.setDemandCode(dto.getDemandCode());
        dspfDemandDevplanDO.setChangeDelayReason(dspfDemandDevplanDO.getChangeDelayReason()==null?"":dspfDemandDevplanDO.getChangeDelayReason()+","+dto.getChangeDelayReason());
        dspfDemandDevplanDO.setUpdateUser(TyAccountContext.getUser().getName());
        dspfDemandDevplanDO.setUpdateDate(new Date());
        dspfDemandDevplanMapper.updateDspfDemandDevplan(dspfDemandDevplanDO);

        //插入调整历史数据
        DspfDemandDevplanEditLogDO dspfDemandDevplanEditLogDO = new DspfDemandDevplanEditLogDO();
        BeanUtil.copyProperties(dspfDemandDevplanDO,dspfDemandDevplanEditLogDO);
        dspfDemandDevplanEditLogDO.setDevPlanLogID(String.valueOf(snowflakeIdComponent.getInstance().nextId()));
        dspfDemandDevplanEditLogDO.setChangeDelayReason(dto.getChangeDelayReason());
        dspfDemandDevplanEditLogDO.setCreateDate(new Date());
        dspfDemandDevplanEditLogDO.setCreateUser(TyAccountContext.getUser().getName());
        dspfDemandDevplanMapper.insertDspfDemandDevplanEditLog(dspfDemandDevplanEditLogDO);
        return ResponseResult.success("操作成功");
    }

    /**
     * 批量删除需求排程
     *
     * @param DevPlanIDs 需要删除的需求排程主键
     * @return 结果
     */
    @Override
    public int deleteDspfDemandDevplanByDevPlanIDs(String[] DevPlanIDs)
    {
        return dspfDemandDevplanMapper.deleteDspfDemandDevplanByDevPlanIDs(DevPlanIDs);
    }

    /**
     * 删除需求排程信息
     *
     * @param DevPlanID 需求排程主键
     * @return 结果
     */
    @Override
    public int deleteDspfDemandDevplanByDevPlanID(String DevPlanID)
    {
        return dspfDemandDevplanMapper.deleteDspfDemandDevplanByDevPlanID(DevPlanID);
    }

    /**
     * 查询需求排程列表
     *
     * @param
     * @return 需求排程
     */
    @Override
    public PageInfo<DspfDemandDevplanDO> selectDspfDemandDevplanList(DspfDemandDevplanQueryDTO queryDTO, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<DspfDemandDevplanDO> list = dspfDemandDevplanMapper.selectDspfDemandDevplanList(queryDTO);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<DspfDemandDevplanEditLogDO> getEditLoglist(DspfDemandDevplanQueryDTO queryDTO, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<DspfDemandDevplanEditLogDO> list = dspfDemandDevplanMapper.getEditLoglist(queryDTO);
        return new PageInfo<>(list);
    }
}
